const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event, context) => {
    try {
        const { fileID } = event
        if (!fileID) {
            throw new Error('缺少文件ID参数')
        }

        // 获取文件临时链接
        const result = await cloud.getTempFileURL({
            fileList: [fileID]
        })

        if (result.fileList && result.fileList.length > 0) {
            const file = result.fileList[0]
            if (file.tempFileURL) {
                return {
                    code: 0,
                    data: {
                        url: file.tempFileURL,
                        status: file.status
                    },
                    message: '获取文件链接成功'
                }
            }
            if (file.errMsg) {
                throw new Error(file.errMsg)
            }
        }
        throw new Error('获取文件链接失败')
    } catch (err) {
        console.error(err)
        return {
            code: -1,
            message: err.message
        }
    }
}